package com.primaryedu.ui.app.leave;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.bean.LeavelistBean;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.ui.BaseActivity;
import com.primaryedu.widget.PullToRefreshView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请假列表
 *
 * @author jun.wang
 * @description
 * @data 2018年1月4日
 */
@SuppressLint("ResourceAsColor")
public class LeaveListActivity extends BaseActivity implements OnClickListener, PullToRefreshView.OnHeaderRefreshListener, PullToRefreshView.OnFooterRefreshListener {
    private ListView listView;
    LeaveListAdapter adapter;
    private PullToRefreshView pullToRefreshView;
    private boolean fistenter = true;
    private int page = 1;
    private boolean uploadMore = false;
    public String s;
    protected RequestQueue requestQueue = null;
    private final static int REQUESTCODELEAVE = 1; // "申请"返回的结果码
    private final static int REQUESTCODEAPPROVE = 2; // "申请"返回的结果码
    private List<LeavelistBean.DataBean.ListBean> leaveLists = new ArrayList<>();
    private List<LeavelistBean.DataBean.ListBean> leavetempList = new ArrayList<>();
    private List<LeavelistBean.DataBean.ListBean> leavemoreLists = new ArrayList<>();
    public List<LeavelistBean.DataBean.ListBean> loadmoreList = new ArrayList<>();// 表示出现刷新之后需要显示的list

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1001:
                    if (null != leavetempList && leavetempList.size() != 0) {
//						newsAdapter = new ExerciseAdapter(getApplicationContext(), NicedialogUtils.getExerciseList(GlobalData.newsLists)) ;
//						newsListView.setAdapter(newsAdapter);
                        adapter = new LeaveListAdapter(LeaveListActivity.this, leavetempList);
                        listView.setAdapter(adapter);
                    }
                    break;
                case 1002:
                    if (leavetempList != null && leavetempList.size() != 0) {
                        adapter.updateView(leavetempList);
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_leave_list);

        init();
        if (GlobalData.getUsertype(getApplicationContext()).contains("8")
                || GlobalData.getUsertype(getApplicationContext()).contains("7")) {
            requestMasterLeavelist(fistenter);
        } else {
            requestLeavelist(fistenter);

        }
    }

    private void requestMasterLeavelist(boolean fistenter) {
        if (fistenter) {
            showLoading("加载中...");
        }
        page = 1;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.askforMasterleaveList,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("response=masterleavelist=" + response);
                        page++;
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {

                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");
                                System.out.println("response=listStr=" + listStr);
                                leaveLists = new Gson().fromJson(listStr,
                                        new TypeToken<List<LeavelistBean.DataBean.ListBean>>() {
                                        }.getType());
                                leavetempList.clear();
                                leavetempList.addAll(leaveLists);
                                handler.sendEmptyMessage(1001);
//								}


                                System.out.println("leaveLists==" + listStr);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("访问失败，请重新刷新下拉刷新！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
//			            //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
//				map.put("status", "1");
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                return map;

            }
        };
        requestQueue.add(stringRequest);
    }

    private void requestMasterLeavemorelist() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.askforMasterleaveList,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("response=masterleavemorelist=" + response);
                        page++;
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                String data = json.getString("data");
                                if (data.contains("list")) {
                                    JSONObject listObj = new JSONObject(data);
                                    String listStr = listObj.getString("list");
                                    System.out.println("response=listStr=" + listStr);
                                    leavemoreLists = new Gson().fromJson(listStr,
                                            new TypeToken<List<LeavelistBean.DataBean.ListBean>>() {
                                            }.getType());

                                    leavetempList.addAll(leavemoreLists);
                                    handler.sendEmptyMessage(1002);
                                } else {
//									if (listStr == null){
                                    showToast("已经加载完全部数据！");
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    private void init() {
        requestQueue = Volley.newRequestQueue(getApplicationContext());
        ((TextView) findViewById(R.id.title)).setText("请假列表");
        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.right).setVisibility(View.VISIBLE);
        findViewById(R.id.right).setOnClickListener(this);
        if (GlobalData.getUsertype(getApplicationContext()).contains("8")
                || GlobalData.getUsertype(getApplicationContext()).contains("7")) {//7:校长 8 ： 请假管理员
            ((TextView) findViewById(R.id.text_right)).setVisibility(View.GONE);
        } else {
            ((TextView) findViewById(R.id.text_right)).setText("申请");
        }
        ((TextView) findViewById(R.id.text_right)).setTextColor(getResources().getColor(R.color.main_button));
        listView = (ListView) this.findViewById(R.id.listView);
        adapter = new LeaveListAdapter(LeaveListActivity.this, leavetempList);
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
                LeavelistBean.DataBean.ListBean lb = leavetempList.get(position);
                if (lb.getType() == 0) {
                    s = "事假";
                } else if (lb.getType() == 1) {
                    s = "病假";
                }

                if (GlobalData.getUsertype(getApplicationContext()).contains("8") ||
                        GlobalData.getUsertype(getApplicationContext()).contains("7")) {//管理员 7：校长  8：请假管理员
                    Intent intent = new Intent(LeaveListActivity.this, LeaveApproveActivtiy.class);
                    intent.putExtra("id", lb.getId());
                    intent.putExtra("staus", lb.getStatus());
                    intent.putExtra("type", s);
                    intent.putExtra("reason", lb.getReason());
                    intent.putExtra("remark", lb.getRemark());
                    intent.putExtra("auditorname", lb.getAuditorName());
                    intent.putExtra("begintime", lb.getBeginTime());
                    intent.putExtra("endtime", lb.getEndTime());
                    intent.putExtra("pic1", lb.getPic1());
                    intent.putExtra("pic2", lb.getPic2());
                    intent.putExtra("pic3", lb.getPic3());
                    startActivityForResult(intent, REQUESTCODEAPPROVE);
                } else {//普通用户
//					Toast.makeText(LeaveListActivity.this,"普通用户",Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(LeaveListActivity.this, LeaveDetailsActivtiy.class);
                    intent.putExtra("staus", lb.getStatus());
                    intent.putExtra("starttime", lb.getBeginTime());
                    intent.putExtra("endtime", lb.getEndTime());
                    intent.putExtra("staus", lb.getStatus());
                    intent.putExtra("id", lb.getId());
                    intent.putExtra("type", s);
                    intent.putExtra("reason", lb.getReason());
                    intent.putExtra("remark", lb.getRemark());
                    intent.putExtra("auditorname", lb.getAuditorName());
                    intent.putExtra("pic1", lb.getPic1());
                    intent.putExtra("pic2", lb.getPic2());
                    intent.putExtra("pic3", lb.getPic3());
                    startActivity(intent);
                }
            }
        });

        pullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
        pullToRefreshView.setOnHeaderRefreshListener(this);
        pullToRefreshView.setOnFooterRefreshListener(this);
        pullToRefreshView.setLastUpdated(new Date().toLocaleString());

    }

    @Override
    protected int BindLayout() {
        return R.layout.activity_leave_list;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.back:
                finish();
                break;

            // 申请
            case R.id.right:
                Intent intent = new Intent(LeaveListActivity.this, LeaveActivity.class);
                startActivityForResult(intent, REQUESTCODELEAVE);
//			 startActivity(intent);
                break;

            default:
                break;
        }

    }

    private void requestLeavelist(final boolean fistenter) {
        if (fistenter) {
            showLoading("加载中...");
        }
        page = 1;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.askforTeacherleaveList,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("response=leavelist=" + response);
                        page++;
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {

                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");
                                System.out.println("response=listStr=" + listStr);
                                leaveLists = new Gson().fromJson(listStr,
                                        new TypeToken<List<LeavelistBean.DataBean.ListBean>>() {
                                        }.getType());
//								if (uploadMore) {
//									loadmoreList.addAll(leaveLists);
//									handler.sendEmptyMessage(1002) ;
//									if (listStr == null){
//										showToast("已经加载完全部数据！");
//									}
//									uploadMore = false;
//
//								}else {
                                leavetempList.clear();
                                leavetempList.addAll(leaveLists);
//									adapter.addAll(leaveLists);
                                handler.sendEmptyMessage(1001);
//								}


                                System.out.println("leaveLists==" + listStr);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("访问失败，请重新刷新下拉刷新！");
//				None,  // 允许遮罩下面控件点击
//				Clear,     // 不允许遮罩下面控件点击
//				Black,     // 不允许遮罩下面控件点击，背景黑色半透明
//				Gradient,   // 不允许遮罩下面控件点击，背景渐变半透明
//				ClearCancel,     // 不允许遮罩下面控件点击，点击遮罩消失
//				BlackCancel,     // 不允许遮罩下面控件点击，背景黑色半透明，点击遮罩消失
//				GradientCancel   // 不允许遮罩下面控件点击，背景渐变半透明，点击遮罩消失
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
//				map.put("status", "1");
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                map.put("userId", GlobalData.getUserId(getApplicationContext()));
                return map;

            }
        };
        requestQueue.add(stringRequest);
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                uploadMore = true;
                if (GlobalData.getUsertype(getApplicationContext()).contains("8")
                        || GlobalData.getUsertype(getApplicationContext()).contains("8")) {
                    requestMasterLeavemorelist();
                } else {
                    requestLeavemorelist();

                }
                pullToRefreshView.onFooterRefreshComplete();

            }

        }, 1500);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (GlobalData.getUsertype(getApplicationContext()).contains("8")
                        || GlobalData.getUsertype(getApplicationContext()).contains("7")) {
                    requestMasterLeavelist(false);
                } else {
                    requestLeavelist(false);
                }
                pullToRefreshView.onHeaderRefreshComplete("更新于:"
                        + Calendar.getInstance().getTime().toLocaleString());
                pullToRefreshView.onHeaderRefreshComplete();
                Toast.makeText(LeaveListActivity.this, "数据刷新完成!", Toast.LENGTH_LONG).show();
            }

        }, 1500);
    }

    private void requestLeavemorelist() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.askforTeacherleaveList,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("response=leavelist=" + response);
                        page++;
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                String data = json.getString("data");
                                if (data.contains("list")) {
                                    JSONObject listObj = new JSONObject(data);
                                    String listStr = listObj.getString("list");
                                    System.out.println("response=listStr=" + listStr);
                                    leavemoreLists = new Gson().fromJson(listStr,
                                            new TypeToken<List<LeavelistBean.DataBean.ListBean>>() {
                                            }.getType());

                                    leavetempList.addAll(leavemoreLists);
                                    handler.sendEmptyMessage(1002);
                                } else {
//									if (listStr == null){
                                    showToast("已经加载完全部数据！");
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                map.put("userId", GlobalData.getUserId(getApplicationContext()));
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // RESULT_OK，判断另外一个activity已经结束数据输入功能，Standard activity result:
        // operation succeeded. 默认值是-1
        if (resultCode == 3) {
            if (requestCode == REQUESTCODELEAVE) {
                requestLeavelist(false);
            }
            if (requestCode == REQUESTCODEAPPROVE) {
//				requestLeavelist(true);
                requestMasterLeavelist(false);
            }
        }
    }
}
